package com.kang.listener;

import catcode.CatCodeUtil;
import catcode.Neko;
import com.kang.GifOperator;
import com.kang.bean.bot.Answer;
import com.kang.bean.bot.Msg;
import com.kang.bean.bot.ResultByQq;
import com.kang.service.subject.AnswerService;
import com.kang.service.subject.ResultByQqService;
import com.kang.service.subject.SubjectService;
import com.kang.websocket.MyWebSocket;
import love.forte.common.ioc.annotation.Beans;
import love.forte.common.ioc.annotation.Depend;
import love.forte.simbot.annotation.Filter;
import love.forte.simbot.annotation.Listen;
import love.forte.simbot.annotation.OnGroup;
import love.forte.simbot.api.message.MessageContent;
import love.forte.simbot.api.message.MessageContentBuilder;
import love.forte.simbot.api.message.MessageContentBuilderFactory;
import love.forte.simbot.api.message.containers.AccountInfo;
import love.forte.simbot.api.message.containers.GroupAccountInfo;
import love.forte.simbot.api.message.containers.GroupInfo;
import love.forte.simbot.api.message.events.GroupMsg;
import love.forte.simbot.api.message.events.GroupMsgRecall;
import love.forte.simbot.api.sender.Sender;
import love.forte.simbot.filter.MatchType;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @program: service
 * @description: 群聊监听器
 * @author: K.faWu
 * @create: 2022-04-28 16:34
 **/
@Beans
@Component
public class GroupListener {
    /**
     * 通过依赖注入获取一个 "消息正文构建器工厂"。
     *
     */
    @Depend
    private final MessageContentBuilderFactory messageContentBuilderFactory;
    private final SubjectService subjectService;
    private final AnswerService answerService;
    private final ResultByQqService resultByQqService;

    public GroupListener(MessageContentBuilderFactory messageContentBuilderFactory, SubjectService subjectService, AnswerService answerService,  ResultByQqService resultByQqService) {
        this.messageContentBuilderFactory = messageContentBuilderFactory;
        this.subjectService = subjectService;
        this.answerService = answerService;
        this.resultByQqService = resultByQqService;
    }

    @OnGroup
    public void onGroupMsg(GroupMsg groupMsg, Sender sender) {
        // 获取消息构建器
        GroupInfo groupInfo = groupMsg.getGroupInfo();
        // 打印群号与名称
        System.out.println(groupInfo.getGroupCode());
        System.out.println(groupInfo.getGroupName());

        String msg = groupMsg.getMsg();
        System.out.println(msg);
        String text = groupMsg.getText();
        System.out.println(text);
        //处理所有图片类消息
        if (msg.contains("[CAT:image,id=")){
            addEmoticon(groupMsg, sender);
        }
        GroupAccountInfo accountInfo = groupMsg.getAccountInfo();
        ResultByQq<Msg> resultByQq = new ResultByQq<>();
        BeanUtils.copyProperties(accountInfo, resultByQq);
        MessageContent msgContent = groupMsg.getMsgContent();
        resultByQqService.msgToResultByQq(resultByQq, msgContent);
        MyWebSocket.sendInfo(resultByQq, groupMsg.getBotInfo().getBotCode(), groupInfo.getGroupCode());
        // 打印此次消息中的 纯文本消息内容。
        // 纯文本消息中，不会包含任何特殊消息（例如图片、表情等）。
        //System.out.println(groupMsg.getText());

        // 打印此次消息中的 消息内容。
        // 消息内容会包含所有的消息内容，也包括特殊消息。特殊消息使用CAT码进行表示。
        // 需要注意的是，绝大多数情况下，getMsg() 的效率低于甚至远低于 getText()
        //System.out.println(groupMsg.getMsg());

        // 获取此次消息中的 消息主体。
        // messageContent代表消息主体，其中通过可以获得 msg, 以及特殊消息列表。
        // 特殊消息列表为 List<Neko>, 其中，Neko是CAT码的封装类型。

        //MessageContent msgContent = groupMsg.getMsgContent();

        // 打印消息主体
        //System.out.println(msgContent);
        // 打印消息主体中的所有图片的链接（如果有的话）
        //List<Neko> imageCats = msgContent.getCats("image");
        //System.out.println("img counts: " + imageCats.size());
//        for (Neko image : imageCats) {
//            System.out.println("Img url: " + image.get("url"));
//        }


        // 获取发消息的人。
        //GroupAccountInfo accountInfo = groupMsg.getAccountInfo();
        // 打印发消息者的账号与昵称。
        //System.out.println(accountInfo.getAccountCode());
        //System.out.println(accountInfo.getAccountNickname());


        // 获取群信息
        //GroupInfo groupInfo = groupMsg.getGroupInfo();

        // 获取消息构建器
        //MessageContentBuilder msgBuilder = messageContentBuilderFactory.getMessageContentBuilder();
        // 获取CAT码工具类实例
        //CatCodeUtil catCodeUtil = CatCodeUtil.getInstance();

        // 构建一个类型为 'face', 参数为 'id=9' 的CAT码。
        // 有很多方法。

        // 1. 通过 codeBuilder 构建CAT码
        // String cat1 = catCodeUtil.getStringCodeBuilder("face", false).key("id").value(9).build();

        // 2. 通过CatCodeUtil.toCat 构建CAT码
        // String cat2 = catCodeUtil.toCat("face", "id=9");

        // 3. 通过模板构建CAT码
        //String cat3 = catCodeUtil.getStringTemplate().face(6);

        // 在cat码前增加一句 '表情' 并发送
        //sender.sendGroupMsg(groupInfo.getGroupCode(), accountInfo.getAccountNickname() + ",我在呢！"+cat3);
    }

    /**
     * 保存表情包
     */
    private void addEmoticon(GroupMsg groupMsg, Sender sender){
        MessageContent msgContent = groupMsg.getMsgContent();
        List<Neko> imageCats = msgContent.getCats("image");
        for (Neko image : imageCats) {
            Answer answer = new Answer();
            GroupAccountInfo accountInfo = groupMsg.getAccountInfo();
            // 打印发消息者的账号与昵称。
            //System.out.println(accountInfo.getAccountCode());
            answer.setPerson(accountInfo.getAccountCode());
            answer.setText(image.get("url"));
            answer.setType("image");
            answer.setWeight(1D);
            answer.setSubId(2L);
            //System.out.println("Img url: " + image.get("url"));
            int i = answerService.addEmoticon(answer);
            if (i != -1){
                //之前没有这张表情包
                /*MessageContentBuilder msgBuilder = messageContentBuilderFactory.getMessageContentBuilder();
                msgBuilder.text("图收下了~").build();
                MessageContent build = msgBuilder.image("http://gchat.qpic.cn/gchatpic_new/1551360792/709733972-2335679169-A96A41CA9603266DA80DCE6E27A6CA74/0?term=2").build();
                //表示感谢
                GroupInfo groupInfo = groupMsg.getGroupInfo();
                sender.sendGroupMsg(groupInfo.getGroupCode(), build);*/
            }
        }
    }

    /**
     * 当有消息撤回
     */
    @Listen(GroupMsgRecall.class)
    public void getRecall(GroupMsgRecall groupMsgRecall, Sender sender){
        MessageContent msgContent = groupMsgRecall.getMsgContent();
        System.out.println("这是撤回的消息： "+ msgContent.getMsg());
        //操作人的信息
        AccountInfo accountInfo = groupMsgRecall.getAccountInfo();
        String accountNickname = accountInfo.getAccountNickname();
        MessageContentBuilder msgBuilder = messageContentBuilderFactory.getMessageContentBuilder();
        //MessageContent content = msgBuilder.text(accountNickname + "撤回一条消息↓").build();
        //sender.sendGroupMsg(groupMsgRecall, content);
        sender.sendGroupMsg(groupMsgRecall, msgContent);
    }

    /**
     * 被@的时候
     */
    @Filter(atBot = true)
    @OnGroup
    public void atBot(GroupMsg groupMsg, Sender sender){
        System.out.println("我被@了"+groupMsg.getMsg());
        // 获取消息构建器
        MessageContentBuilder msgBuilder = messageContentBuilderFactory.getMessageContentBuilder();
        GroupInfo groupInfo = groupMsg.getGroupInfo();
        String text = groupMsg.getText().trim();
        String type = "public";
        Answer answer;
        answer = subjectService.getAnswer(text, type);
        if (answer==null){
            type = "group";
            answer = subjectService.getAnswer(text, type);
        }

        if (answer==null ){
            answer = new Answer();
            answer.setText("是我太笨了，听不懂你说的什么");
            answer.setType("text");
        }

        String type1 = answer.getType();
        String text2 = answer.getText();
        if ("text".equals(type1)){
            text2 = text2.replaceAll("\\\\n", "\n");
            MessageContent content = msgBuilder.text(text2).build();
            sender.sendGroupMsg(groupInfo.getGroupCode(), content);
        }else if("image".equals(type1)){
            //图片
            MessageContent build = msgBuilder.image(answer.getText()).build();
            // 直接通过这个msg发送。
            sender.sendGroupMsg(groupInfo.getGroupCode(), build);
        }
    }



    @Filter(value = "可达鸭", matchType = MatchType.STARTS_WITH)
    @OnGroup
    public void duck(GroupMsg groupMsg, Sender sender) throws IOException {// 获取消息构建器
        MessageContentBuilder msgBuilder = messageContentBuilderFactory.getMessageContentBuilder();
        String text = groupMsg.getMsg();
        String[] split = text.split(" ");
        if (split.length >= 3) {
            String path = setDuck(split[1], split[2]);
            MessageContent build = msgBuilder.image(path).build();
            sender.sendGroupMsg(groupMsg, build);
        }

    }


    public String setDuck(String leftStr, String rightStr) throws IOException {
        String dirPath = "D:/image/";
        String path = "D:\\image\\res.gif";
        //修改展示的类型
        String left = catToUrl(leftStr);
        boolean leftFlag = left.equals(leftStr);
        String right = catToUrl(rightStr);
        boolean rightFlag = right.equals(rightStr);


        List<BufferedImage> images = new ArrayList<>();
        for (int i = 0 ; i < 17;i++) {
            File outFile = new File(dirPath + i + ".png");
            BufferedImage image = ImageIO.read(outFile);
            switch (i) {
                case 0: draw(image, left,45, 107, leftFlag);break;
                case 1: draw(image, left,41, 95, leftFlag);break;
                case 2: draw(image, left,36, 76, leftFlag);break;
                case 3:
                case 4: draw(image, right,322, 66, rightFlag);break;
                case 5: draw(image, right,326, 79, rightFlag);break;
                case 6: draw(image, right,326, 72, rightFlag);break;
                case 7: draw(image, right,326, 75, rightFlag);break;
                case 8: draw(image, right,331, 75, rightFlag);break;
                case 9: draw(image, right,328, 76, rightFlag);break;
                case 10: draw(image, right,325, 67, rightFlag);break;
                case 11: draw(image, right,328, 70, rightFlag);break;
                case 12:
                case 13: draw(image, left,57, 93, leftFlag);break;
                case 14: draw(image, left,53, 85, leftFlag);break;
                case 15: draw(image, left,69, 98, leftFlag);break;
                case 16: draw(image, left,62, 90, leftFlag);break;
                case 17: draw(image, left,56, 85, leftFlag);break;
                default: break;
            }
            images.add(image);
        }
        GifOperator.imagesToGif(images, path);
        return path;
    }

    private void draw(BufferedImage image, String str, int x, int y, boolean flag) throws IOException {
        Graphics2D graphics = image.createGraphics();
        if (flag) {
            //文字
            graphics.setColor(Color.black);
            // 旋转
//            if (x>300){
//                graphics.rotate(122, x, y);
//
//            }
            graphics.setFont(new Font("黑体", Font.BOLD, 30));
            graphics.drawString(str,x, y);
        } else {
            //图片
            URL url = new URL(str);
            BufferedImage b = ImageIO.read(url);
            int width = b.getWidth();
            int height = b.getHeight();
//            int[] ints = new int[width * height];
//            ints = b.getRGB(0, 0, width, height, ints, 0, width);
//            image.setRGB(x, y, width, height, ints, 0, width);

            // 缩放画板
            //graphics.scale(0.5, 0.5);
            // 此时的宽和高如果大于画板则无效，自动缩放到充满画板
            graphics.drawImage(b, x, y-20, 100, 100, null);
        }
    }

    public String catToUrl(String str){
        if (str.startsWith("[CAT:")){
            CatCodeUtil codeUtil = CatCodeUtil.getInstance();
            Neko neko = codeUtil.getNeko(str);
            String type = neko.getType();

            if ("face".equals(type)) {
                String id = neko.get("id");
                return "http://emoji.fawukang.top/s"+id+".png ";
            } else if ("image".equals(type)) {
                return neko.get("url");
            }
        }
        return str;
    }
}
